package com.motus.pm.daoImpl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.motus.pm.dao.BaseDao;


/*
 * 注意：此类不应该实例化，也就是说不要加上@Repository注解，否则spring容器初始化的时候会报错，因为该类必须要确定具体的T类型才可以实例化
 */
public class BaseDaoImpl<T> implements BaseDao<T> {
	
	Class<T> clazz;
    ParameterizedType pt;
    
    @Autowired
    protected SessionFactory sessionFactory;
    
    @SuppressWarnings("unchecked")
	public BaseDaoImpl() {
        pt = (ParameterizedType)this.getClass().getGenericSuperclass();     
        clazz = (Class<T>)pt.getActualTypeArguments()[0];
    }

	@Override
	public void save(T entity) {
		Session session=sessionFactory.getCurrentSession();
		session.save(entity);
	}

	@Override
	public void delete(T entity) {
		Session session=sessionFactory.getCurrentSession();
		session.delete(entity);
	}

	@Override
	public void update(T entity) {
		Session session=sessionFactory.getCurrentSession();
		session.update(entity);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T getById(Serializable id) {
		Session session=sessionFactory.getCurrentSession();
		return (T) session.get(clazz, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> getAll() {
		Session session=sessionFactory.getCurrentSession();
		String hql="from "+clazz.getSimpleName();
		return session.createQuery(hql).list();
	}
}

